package com.cx.jvm;

import lombok.Getter;
import lombok.Setter;

import java.io.*;

/**
 * 自定义类加载器
 * 加载指定路径下的类
 * @Author:cxy
 * @Date:2021/11/24 20:28
 */
@Getter
@Setter
public class MyClassLoader extends ClassLoader{

    // 默认加载路径
    private String path = "/jvm/define";

    // 类加载器名称
    private String name;

    // 文件类型
    private final String fileType = ".class";


    public MyClassLoader(String name) {
        super();
        this.name = name;
    }

    public MyClassLoader(ClassLoader parent, String name) {
        super(parent);
        this.name = name;
    }


    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] b =  loadClassData(name);
        return defineClass(name,b,0,b.length);
    }

    /**
     * 自定义类加载数据
     * @param name 类的全限定名称 eg: com.cx.jvm.Xxx
     * @return 类信息
     */
    private byte[] loadClassData(String name) {
        byte[] data = null;
        InputStream in = null;
        name = name.replace(".","/");
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {
            in = new FileInputStream(new File(path + name + fileType));
            int len;
            while (-1!=(len = in.read())){
                outputStream.write(len);
            }
            data = outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert in != null;
                in.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data;
    }

    @Override
    public String toString() {
        return "MyClassLoader{" +
                "name='" + name + '\'' +
                '}';
    }
}
